﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebUI.Models;
using System.Web.Security;
using System.Data.Objects.SqlClient;
using System.Linq.Expressions;
using System.Collections;

namespace WebUI.Controllers
{
    [Authorize(Roles = "Doctor,Admin,Engineer")]
    [GZip()]
    public class DoctorController : _SiteBaseController
    {


        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.Status = DB.EnumValues.Where(v => v.EnumID == "01001");
            //ViewBag.Departments = DB.Departments;
            ViewBag.Departments = new Department[] { SiteUser.Department };
            ViewBag.Hospitals = DB.Hospitals_Fixed;
            ViewBag.Users = DB.Doctors.Where(v => v.DepartmentID == SiteUser.DepartmentID); // DB.Doctors;
            ViewBag.HealthStatus = DB.EnumValues.Where(v => v.EnumID == "01003");
            ViewBag.utid = Request["utid"];
            ViewBag._ReadOnly = "True".Equals(Request["_ReadOnly"], StringComparison.CurrentCultureIgnoreCase);
            Response.Cache.SetExpires(DateTime.MinValue);

            base.OnActionExecuting(filterContext);
        }

        public ActionResult Index() { return RedirectToAction("QizSessionList"); }

        /////////////////////随访单

        //
        // GET: /SystemMgr/
        public ActionResult SuiFangDanMgr()
        {

            return View();
        }

        public ActionResult DrEdit()
        {
            //if (ID == Guid.Empty) return PartialView(new aspnet_Users());
            //else 
            return PartialView(DB.aspnet_Users.Where(v => v.UserId == SiteUser.UserId).FirstOrDefault());
        }
        [HttpPost]
        public ActionResult DrEdit(aspnet_Users m, string Pwd)
        {
            if (!string.IsNullOrEmpty(Pwd))
            {
                var mu = Membership.GetUser(m.UserName);
                mu.ChangePassword(mu.ResetPassword(), Pwd);
            }
            var tm = m;
            tm = DB.aspnet_Users.Where(v => v.UserId == m.UserId).FirstOrDefault();
            tm.MobileAlias = m.MobileAlias;
            DB.SaveChanges();
            return RedirectToAction("SFDList");
        }

        public ActionResult SFDList()
        {
            var m = DB.QizSubjects;
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SFDList(string Search)
        {
            if (string.IsNullOrWhiteSpace(Search))
            {
                var m = DB.QizSubjects;
                return PartialView(m);
            }
            else
            {
                IQueryable<QizSubject> m = null;
                DateTime dt = DateTime.MinValue;
                if (DateTime.TryParse(Search, out dt))
                {
                    m = DB.QizSubjects.Where(v => (v.CreateTime > dt.AddMonths(-1) && v.CreateTime < dt.AddMonths(1)));
                }
                else
                {
                    m = DB.QizSubjects.Where(v =>
                        v.ID.Contains(Search) ||
                        v.Title.Contains(Search) ||
                        v.Department.DepName.Contains(Search) ||
                        v.Owner.UserName.Contains(Search) ||
                        v.Creator.UserName.Contains(Search) ||
                        v.StatusRef.OptionTitle.Contains(Search) ||
                        v.Tag.Contains(Search));
                }
                return PartialView(m);
            }
        }
        [HttpGet]
        public ActionResult SFDEdit(string ID)
        {
            ViewBag.Templates = DB.QizTemplates.Where(v => v.StatusID == "101");

            if (string.IsNullOrEmpty(ID)) return PartialView(DB.QizSubjects.CreateObject());
            else return PartialView(DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault());
        }
        [HttpPost]
        public ActionResult SFDEdit(QizSubject m, bool IsInitFromTemplate, string QizTemplateID)
        {
            //if (ModelState.IsValid)
            //{
            if (string.IsNullOrEmpty(m.ID))
            {
                m.ID = DB.NewID();
                DB.QizSubjects.AddObject(m);
            }
            else
            {
                DB.QizSubjects.Where(v => v.ID == m.ID).First();
                DB.QizSubjects.ApplyCurrentValues(m);
                m = DB.QizSubjects.Where(v => v.ID == m.ID).First();
            }
            if (IsInitFromTemplate)
            {
                var t = DB.QizTemplates.Where(v => v.QizFormTemplateID == QizTemplateID).First();
                var tqis = t.QizTemplateDefines.Select(v => v.QizItem);
                var cqis = m.QizSubjectDefines.Select(v => v.QizItem);

                var toremove = cqis.Except(tqis);
                var toadd = tqis.Except(cqis);

                foreach (var item in m.QizSubjectDefines.Where(v => toremove.Contains(v.QizItem)))
                {
                    m.QizSubjectDefines.Remove(item);
                }
                int sidx = 0;
                foreach (var item in m.QizSubjectDefines)
                {
                    item.SortIdx = sidx++;
                }
                foreach (var item in toadd)
                {
                    m.QizSubjectDefines.Add(new QizSubjectDefine() { ID = DB.NewID(), QizItem = item, SortIdx = sidx++ });
                }
            }
            DB.SaveChanges();

            return RedirectToAction("SFDList");
            //}
            //else
            //{
            //    throw new ArgumentException("输入不正确。");
            //}
        }

        public ActionResult SFDDelete(string ID)
        {
            var m = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            DB.QizSubjects.DeleteObject(m);
            DB.SaveChanges();
            return RedirectToAction("SFDList");
        }
        public ActionResult SFDView(string ID)
        {
            return View(DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault());
        }
        /////////////////////////////////Ming xi



        [HttpGet]
        public ActionResult SftMingXiMgr(string ID)
        {
            var m = DB.QizSubjects;
            ViewBag.QizSubjectID = ID;
            return View(m);
        }
        [HttpGet]
        public ActionResult SftMingXiList(string ID)
        {
            var m = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView(m);
        }



        [HttpGet]
        public ActionResult SftMingXiAdd(string ID)
        {
            var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            var qis = from v in om.QizSubjectDefines
                      select v.QizItemID;

            var m = DB.QizItems.Where(v => !qis.Contains(v.QizItemID));
            ViewBag.ID = ID;
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SftMingXiAdd(string ID, string[] Selection)
        {
            var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();

            var ms = om.QizSubjectDefines.Count > 0 ? om.QizSubjectDefines.Max(v => v.SortIdx) : 0;

            var m = DB.QizItems.Where(v => Selection.Contains(v.QizItemID));
            foreach (var v in m)
            {
                var nm = new QizSubjectDefine() { QizItemID = v.QizItemID, QizSubjectID = ID, SortIdx = ms++, ID = DB.NewID() };
                om.QizSubjectDefines.Add(nm);
            }
            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = ID });
        }



        [HttpGet]
        public ActionResult SftDrAdd(string ID)
        {
            var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            var l = from v in om.QizSubjectObjForDoctors
                    select v.DoctorID;

            var m = DB.Doctors.Where(v => !l.Contains(v.UserId));
            ViewBag.ID = ID;
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SftDrAdd(string ID, string[] Selection)
        {
            var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();

            var m = DB.Doctors.Where(v => Selection.Contains(v.UserName));

            foreach (var v in m)
            {
                var nm = new QizSubjectDoctor() { ID = DB.NewID(), aspnet_Users = v, QizSubject = om };
                om.QizSubjectDoctors.Add(nm);
            }
            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = ID });
        }


        [HttpGet]
        public ActionResult SftRecuperAdd(string ID)
        {
            var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            var l = from v in om.QizSubjectRecupers
                    select v.RecuperID;

            var m = DB.Recupers.Where(v => !l.Contains(v.RecuperID));
            ViewBag.ID = ID;
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SftRecuperAdd(string ID, string[] Selection)
        {
            var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();

            var m = DB.Recupers.Where(v => Selection.Contains(v.User.UserName));

            foreach (var v in m)
            {
                var nm = new QizSubjectRecuper() { ID = DB.NewID(), Recuper = v, QizSubject = om };
                om.QizSubjectRecupers.Add(nm);
            }
            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = ID });
        }

        [HttpGet]
        public ActionResult SortSftMingXi(string ID, string Sort)
        {
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();

            var om = DB.QizSubjectDefines.Where(v => v.QizSubjectID == m.QizSubjectID && v.SortIdx == m.SortIdx + (Sort == "U" ? -1 : 1)).FirstOrDefault();

            if (null != om)
            {
                var t = m.SortIdx; m.SortIdx = om.SortIdx; om.SortIdx = t;
            }
            else
            {
                //m.SortIdx = m.SortIdx + (Sort == "U" ? -1 : 1);
            }
            DB.SaveChanges();

            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });
        }
        [HttpGet]
        public ActionResult DelSftMingXi(string ID)
        {
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
            DB.QizSubjectDefines.DeleteObject(m);

            foreach (var item in DB.QizSubjectDefines.Where(v => v.QizSubjectID == m.QizSubjectID && v.SortIdx > m.SortIdx))
            {
                item.SortIdx = item.SortIdx - 1;
            }
            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });
        }
        [HttpGet]
        public ActionResult DelSftDr(string ID)
        {
            var m = DB.QizSubjectDoctors.Where(v => v.ID == ID).FirstOrDefault();
            DB.QizSubjectDoctors.DeleteObject(m);

            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });
        }
        [HttpGet]
        public ActionResult DelSftRecuper(string ID)
        {
            var m = DB.QizSubjectRecupers.Where(v => v.ID == ID).FirstOrDefault();
            DB.QizSubjectRecupers.DeleteObject(m);

            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });
        }

        public ActionResult QizSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSession>> m = null)
        {

            ViewBag.Subjects = DB.QizSubjects.Where(q => q.DepID == SiteUser.DepartmentID);//&& q.StatusID != "104");
            return ViewOrPartial(Services.QizSessionListForDoctor(m));
        }
        public string DefaultDateTimeFormat = "yyyy-MM-dd HH:mm";
        public string DefaultDateFormat = "yyyy-MM-dd";

        public ActionResult QizSessionListExport(string ExportType, string CurrentFilterOfJson)
        {
            var tm = Services.ParseListViewModeJsonFilter<QizSession>(CurrentFilterOfJson);
            if ("exportsession".Equals(ExportType, StringComparison.CurrentCultureIgnoreCase))
            {
                var data = Services.QizSessionListForDoctor(tm, true).Data;
                string[] titles = "常规随访名称,填报人,填报时间,填报方式,填报人编号,性别,出生日期,手机号,其它手机,家庭电话,家庭其它,其它电话,亲属其它,患者来源,身高,体重,证件类型,证件号,社保号,邮编,地址,电子邮箱,随访类型,主管医生,入院日期,出院日期,病案号,手术日期,出院诊断,采取手术,特殊医用耗材,自动诊断结果,填报质量".Split(',');
                string fn = "基本随访数据导出";
                List<string[]> tempexportdata = null;
                #region set tempexportdata value
                tempexportdata = data.ToList().Select(v => new string[] {
                    v.QizSubject.Title,
                    v.aspnet_Users.UserName,
                    v.Timemark.ToString(DefaultDateTimeFormat),
                    "网络",
                    v.Recuper.RecuperID,
                    v.aspnet_Users.Gender,
                    v.aspnet_Users.BirthDay.ToString(DefaultDateFormat),
                    v.aspnet_Users.MobileAlias,
                    v.aspnet_Users.MobileAliasB,
                    v.aspnet_Users.HomePhone,
                    v.aspnet_Users.HomePhoneB,
                    v.aspnet_Users.OtherPhone,
                    v.aspnet_Users.OtherPhoneB,
                    v.aspnet_Users.HuanZheLaiYuan,
                    v.aspnet_Users.UserHeight,
                    v.aspnet_Users.UserWeight,
                    v.aspnet_Users.IDCodeType,
                    v.aspnet_Users.IDCode,
                    v.aspnet_Users.SheBaoHao,
                    v.aspnet_Users.PostCode,
                    v.aspnet_Users.Address,
                    v.aspnet_Users.Email,
                    v.Recuper.SuiFangLeiXing,
                    v.Recuper.Doctor.UserName,
                    v.Recuper.EnHospDay.ToString(DefaultDateFormat),
                    v.Recuper.DeHospDay==DateTime.MinValue?string.Empty:v.Recuper.DeHospDay.ToString(DefaultDateFormat),
                    v.Recuper.BingAnHao.ToString(),
                    v.Recuper.ZhuYuanYiSheng,
                    v.Recuper.ZhenDuanS,
                    v.Recuper.ShouShuS,
                    v.Recuper.BeiZhu,
                    v.SessionAutoEvaluation,
                    v.TianBaoZhiLiang//,
                    //v.QizSubjectDefine.QizItem.Title,
                    //v.QizSubjectDefine.QizItem.Unit,
                    //v.UserValue,
                    //v.ValueAutoEvaluation
                }).ToList();
                #endregion

                Response.Buffer = true;
                Response.ContentType = "application/vnd.ms-excel";
                return File(WebUI.Services.DocumentServices.CreateSpreadsheetDocument(fn, titles, tempexportdata), "application/vnd.ms-excel", Url.Encode(fn + ".xlsx"));
            }
            else if ("exportdetail".Equals(ExportType, StringComparison.CurrentCultureIgnoreCase))
            {
                //var tm2 = Services.ParseListViewModeJsonFilter<QizSessionDetail>(CurrentFilterOfJson);
                var data = Services.QizSessionListForDoctor_Detail(tm).Data;

                List<string[]> tempexportdata = null;
                #region set tempexportdata value
                tempexportdata = data.ToList().Select(v => new string[] {
                    v.QizSession.QizSubject.Title,
                    v.QizSession.aspnet_Users.UserName,
                    v.QizSession.Timemark.ToString(DefaultDateTimeFormat),
                    "网络",
                    v.QizSession.Recuper.RecuperID,
                    v.QizSession.aspnet_Users.Gender,
                    v.QizSession.aspnet_Users.BirthDay.ToString(DefaultDateFormat),
                    v.QizSession.aspnet_Users.MobileAlias,
                    v.QizSession.aspnet_Users.MobileAliasB,
                    v.QizSession.aspnet_Users.HomePhone,
                    v.QizSession.aspnet_Users.HomePhoneB,
                    v.QizSession.aspnet_Users.OtherPhone,
                    v.QizSession.aspnet_Users.OtherPhoneB,
                    v.QizSession.aspnet_Users.HuanZheLaiYuan,
                    v.QizSession.aspnet_Users.UserHeight,
                    v.QizSession.aspnet_Users.UserWeight,
                    v.QizSession.aspnet_Users.IDCodeType,
                    v.QizSession.aspnet_Users.IDCode,
                    v.QizSession.aspnet_Users.SheBaoHao,
                    v.QizSession.aspnet_Users.PostCode,
                    v.QizSession.aspnet_Users.Address,
                    v.QizSession.aspnet_Users.Email,
                    v.QizSession.Recuper.SuiFangLeiXing,
                    v.QizSession.Recuper.Doctor.UserName,
                    v.QizSession.Recuper.EnHospDay.ToString(DefaultDateFormat),
                    v.QizSession.Recuper.DeHospDay==DateTime.MinValue?string.Empty:v.QizSession.Recuper.DeHospDay.ToString(DefaultDateFormat),
                    v.QizSession.Recuper.BingAnHao.ToString(),
                    v.QizSession.Recuper.ZhuYuanYiSheng,
                    v.QizSession.Recuper.ZhenDuanS,
                    v.QizSession.Recuper.ShouShuS,
                    v.QizSession.Recuper.BeiZhu,
                    //v.QizSession.SessionAutoEvaluation,
                    v.QizSubjectDefine.QizItem.Title,
                    v.QizSubjectDefine.QizItem.Unit,
                    v.UserValue,
                    v.ValueAutoEvaluation,
                    v.QizSession.TianBaoZhiLiang
                }).ToList();
                #endregion

                Response.Buffer = true;
                Response.ContentType = "application/vnd.ms-excel";
                return File(WebUI.Services.DocumentServices.CreateSpreadsheetDocument("随访数据",
                    "常规随访名称,填报人,填报时间,填报方式,填报人编号,性别,出生日期,手机号,其它手机,家庭电话,家庭其它,其它电话,亲属其它,患者来源,身高,体重,证件类型,证件号,社保号,邮编,地址,电子邮箱,随访类型,主管医生,入院日期,出院日期,病案号,手术日期,出院诊断,采取手术,特殊医用耗材,指标,单位,填报值,自动诊断结果,填报质量".Split(','),
                    tempexportdata), "application/vnd.ms-excel", Url.Encode("详细填报指标导出.xlsx"));
            }
            else
            {
                return Content("<script type='text/javascript'>alert('数据导出错误。');window.close();</script>");
            }

        }

        public ActionResult QizSmsSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> m = null)
        {
            ViewBag.Subjects = DB.QizSubjectObjForDoctors.Where(q => q.QizSubject.DepID == SiteUser.DepartmentID).Select(v => v.QizSmsSubject).Distinct();
            return ViewOrPartial(Services.QizSmsSessionListForDoctor(m));
        }

        public ActionResult QizSmsSessionListExport(string ExportType, string CurrentFilterOfJson)
        {
            var tm = Services.ParseListViewModeJsonFilter<QizSmsSession>(CurrentFilterOfJson);
            if ("exportsession".Equals(ExportType, StringComparison.CurrentCultureIgnoreCase))
            {
                var data = Services.QizSmsSessionListForDoctor(tm, true).Data;

                List<string[]> tempexportdata = null;
                #region set tempexportdata value
                tempexportdata = data.ToList().Select(v => new string[] {
                    v.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.Title,
                    v.QizSmsSubjectMonthIdx.QizSmsSubject.Title,
                    //v.QizSmsSubjectMonthIdx.LastMonthIdx.ToString()+"~"+v.QizSmsSubjectMonthIdx.MonthIdx.ToString(),
                    v.QizSmsSubjectMonthIdx.SmsSendingMonthIdx.ToString(),
                    v.Recuper.User.UserName,
                    v.Timemark.ToString(DefaultDateTimeFormat),
                    "网络",
                    v.Recuper.RecuperID,
                    v.Recuper.User.Gender,
                    v.Recuper.User.BirthDay.ToString(DefaultDateFormat),
                    v.Recuper.User.MobileAlias,
                    v.Recuper.User.MobileAliasB,
                    v.Recuper.User.HomePhone,
                    v.Recuper.User.HomePhoneB,
                    v.Recuper.User.OtherPhone,
                    v.Recuper.User.OtherPhoneB,
                    v.Recuper.User.HuanZheLaiYuan,
                    v.Recuper.User.UserHeight,
                    v.Recuper.User.UserWeight,
                    v.Recuper.User.IDCodeType,
                    v.Recuper.User.IDCode,
                    v.Recuper.User.SheBaoHao,
                    v.Recuper.User.PostCode,
                    v.Recuper.User.Address,
                    v.Recuper.User.Email,
                    v.Recuper.SuiFangLeiXing,
                    v.Recuper.Doctor.UserName,
                    v.Recuper.EnHospDay.ToString(DefaultDateFormat),
                    v.Recuper.DeHospDay==DateTime.MinValue?string.Empty:v.Recuper.DeHospDay.ToString(DefaultDateFormat),
                    v.Recuper.BingAnHao.ToString(),
                    v.Recuper.ZhuYuanYiSheng,
                    v.Recuper.ZhenDuanS,
                    v.Recuper.ShouShuS,
                    v.Recuper.BeiZhu,
                    v.SessionAutoEvalution//,
                    //v.QizSubjectDefine.QizItem.Title,
                    //v.QizSubjectDefine.QizItem.Unit,
                    //v.UserValue,
                    //v.ValueAutoEvaluation
                }).ToList();
                #endregion
                Response.Buffer = true;
                Response.ContentType = "application/vnd.ms-excel";

                return File(WebUI.Services.DocumentServices.CreateSpreadsheetDocument("随访数据",
                    "常规随访名称,短信随访名称,随访月份,填报人,填报时间,填报方式,填报人编号,性别,出生日期,手机号,其它手机,家庭电话,家庭其它,其它电话,亲属其它,患者来源,身高,体重,证件类型,证件号,社保号,邮编,地址,电子邮箱,随访类型,主管医生,入院日期,出院日期,病案号,手术日期,出院诊断,采取手术,特殊医用耗材,自动诊断结果".Split(','),
                    tempexportdata), "application/vnd.ms-excel", Url.Encode("基本短信随访数据导出.xlsx"));
            }
            else if ("exportdetail".Equals(ExportType, StringComparison.CurrentCultureIgnoreCase))
            {
                var data = Services.QizSmsSessionListForDoctor_Detail(tm).Data;

                List<string[]> tempexportdata = null;
                #region set tempexportdata value
                tempexportdata = data.ToList().Select(v => new string[] {
                    v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.Title,
                    v.QizSmsSession.QizSmsSubjectMonthIdx.QizSmsSubject.aspnet_Users.UserName,
                    v.QizSmsSession.Timemark.ToString(DefaultDateTimeFormat),
                    "网络",
                    v.QizSmsSession.Recuper.RecuperID,
                    v.QizSmsSession.Recuper.User.Gender,
                    v.QizSmsSession.Recuper.User.BirthDay.ToString(DefaultDateFormat),
                    v.QizSmsSession.Recuper.User.MobileAlias,
                    v.QizSmsSession.Recuper.User.MobileAliasB,
                    v.QizSmsSession.Recuper.User.HomePhone,
                    v.QizSmsSession.Recuper.User.HomePhoneB,
                    v.QizSmsSession.Recuper.User.OtherPhone,
                    v.QizSmsSession.Recuper.User.OtherPhoneB,
                    v.QizSmsSession.Recuper.User.HuanZheLaiYuan,
                    v.QizSmsSession.Recuper.User.UserHeight,
                    v.QizSmsSession.Recuper.User.UserWeight,
                    v.QizSmsSession.Recuper.User.IDCodeType,
                    v.QizSmsSession.Recuper.User.IDCode,
                    v.QizSmsSession.Recuper.User.SheBaoHao,
                    v.QizSmsSession.Recuper.User.PostCode,
                    v.QizSmsSession.Recuper.User.Address,
                    v.QizSmsSession.Recuper.User.Email,
                    v.QizSmsSession.Recuper.SuiFangLeiXing,
                    v.QizSmsSession.Recuper.Doctor.UserName,
                    v.QizSmsSession.Recuper.EnHospDay.ToString(DefaultDateFormat),
                    v.QizSmsSession.Recuper.DeHospDay==DateTime.MinValue?string.Empty:v.QizSmsSession.Recuper.DeHospDay.ToString(DefaultDateFormat),
                    v.QizSmsSession.Recuper.BingAnHao.ToString(),
                    v.QizSmsSession.Recuper.ZhuYuanYiSheng,
                    v.QizSmsSession.Recuper.ZhenDuanS,
                    v.QizSmsSession.Recuper.ShouShuS,
                    v.QizSmsSession.Recuper.BeiZhu,
                    //v.QizSession.SessionAutoEvaluation,
                    v.QizSmsSubjDefine.QizSubjectDefine.QizItem.Title,
                    v.QizSmsSubjDefine.QizSubjectDefine.QizItem.Unit,
                    v.UserValue,
                    v.ValueAutoEvalution
                }).ToList();
                #endregion

                Response.Buffer = true;
                Response.ContentType = "application/vnd.ms-excel";
                return File(WebUI.Services.DocumentServices.CreateSpreadsheetDocument("随访数据",
                    "常规随访名称,填报人,填报时间,填报方式,填报人编号,性别,出生日期,手机号,其它手机,家庭电话,家庭其它,其它电话,亲属其它,患者来源,身高,体重,证件类型,证件号,社保号,邮编,地址,电子邮箱,随访类型,主管医生,入院日期,出院日期,病案号,手术日期,出院诊断,采取手术,特殊医用耗材,指标,单位,填报值,自动诊断结果".Split(','),
                    tempexportdata), "application/vnd.ms-excel", Url.Encode("详细短信填报指标导出.xlsx"));
            }
            else
            {
                return Content("<script type='text/javascript'>alert('数据导出错误。');window.close();</script>");
            }

        }

        [HttpGet]
        public ActionResult QizSmsSessionView(string ID)
        {
            var m = DB.QizSmsSessions.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView(m);
        }
        [HttpPost]
        public ActionResult QizSmsSessionView(QizSmsSession smsSession)
        {
            var m = DB.QizSmsSessions.Where(v => v.ID == smsSession.ID).FirstOrDefault();
            foreach (var item in m.QizSmsSessionDetails)
            {
                var itemkey = item.ID;
                var rawuserval = ValueProvider.GetValue(itemkey) as System.Web.Mvc.ValueProviderResult;
                item.UserValue = rawuserval.AttemptedValue;
            }
            m.Timemark = smsSession.Timemark;
            DB.SaveChanges();

            return RedirectToAction("QizSmsSessionList");
        }

        [HttpGet]
        public ActionResult QizSessionEdit(string SubjectID, string ID, string RefAttID, string RecuperID)
        {
            var TokenID = DateTime.Now.Ticks.ToString();
            ViewBag.TokenID = TokenID;
            Session["Fix_QizSessionEdit_Token_" + TokenID] = "Yes";

            if (!string.IsNullOrWhiteSpace(RecuperID))
            {
                Session["Fix_QizSessionEdit_TempSid"] = ID;
                var m = Services.QizSessionEditInner_Get(SubjectID, ID, RefAttID);
                return ViewOrPartial(m);
            }

            if (string.IsNullOrWhiteSpace(ID))
            {
                bool hasRefItem = false;
                QizSessionDetail di = null;
                if (!string.IsNullOrEmpty(RefAttID))
                {
                    di = DB.QizSessionDetails.First(v => v.ID == RefAttID);
                    hasRefItem = true;
                }

                var sm = DB.QizSubjects.Where(v => v.ID == SubjectID).First();

                var m = new QizSession() { QizSubject = sm, ID = "-1", Timemark = DateTime.MinValue, CreationTime = DateTime.Now };
                if (hasRefItem) m.PID = di.QizSessionID;
                foreach (var item in sm.QizSubjectDefines)
                {
                    var qd = new QizSessionDetail();
                    qd.ID = item.ID;
                    qd.QizSession = m;
                    qd.QizSubjectDefine = item;
                    if (hasRefItem && item.QizItem.Type == "206")
                    {//如果引用了某个附件,而且有附件字段，则(现在只)把引用附件放到自己的附件位。
                        qd.UserValue = di.UserValue;
                        hasRefItem = false;
                    }
                    m.QizSessionDetails.Add(qd);//new QizSessionDetail() {QizSessionID="0", QizSubjectDefine=item});
                }

                return ViewOrPartial(m);

            }

            else
            {
                var m = DB.QizSessions.Where(v => v.ID == ID).FirstOrDefault();
                Session["Fix_QizSessionEdit_TempSid"] = ID;
                return ViewOrPartial(m);
            }
        }

        [HttpPost]
        public ActionResult TianBaoZhiLiangEdit(string SessionID, string TianBaoZhiLiang, string TianBaoZhiLiang_Other)
        {
            var m = DB.QizSessions.FirstOrDefault(v => v.ID == SessionID);
            if (null == m) throw new SiteException("操作目标不正确。");
            m.TianBaoZhiLiang = Services.DepartmentProfileSettingArrayEditor("TianBaoZhiLiang", TianBaoZhiLiang);
            DB.SaveChanges();
            return null;
        }

        [HttpGet]
        public ActionResult QizSessionDel(string ID)
        {
            var m = DB.QizSessions.Where(v => v.ID == ID).FirstOrDefault();
            DB.QizSessions.DeleteObject(m);

            foreach (var item in DB.QizSessionDetails.Where(v => v.QizSessionID == m.ID))
            {
                DB.QizSessionDetails.DeleteObject(item);
            }
            DB.SaveChanges();
            return RedirectToAction("QizSessionList", new { ID = m.QizSubjectID });
        }


        ////////////////////////////患者信息

        public ActionResult RecuperMgr()
        {
            return View();
        }

        public ActionResult SubjectRecuperMgr(ListViewModel<CommonSearchValues2, IQueryable<Recuper>> m = null)
        {
            return View(SiteUser.Department.QizSubjects);
        }
        public ActionResult SubjectRecuperListEdit(string SubjectID, string[] RecuperIDs, string[] SubjSelection, string[] SmsSubjSelection)
        {
            List<QizSubjectObjForDoctor> inviteList = new List<QizSubjectObjForDoctor>();
            for (int i = 0; i < RecuperIDs.Length; i++)
            {
                //var uid = Guid.Parse(UserIDs[i]);
                var uid = RecuperIDs[i];
                var m = DB.QizSubjectObjForDoctors.Where(v => v.QizSubjectID == SubjectID && v.DoctorID == SiteUser.UserId && v.RecuperID == uid).FirstOrDefault();

                if (SubjSelection != null && SubjSelection.Contains(RecuperIDs[i]))
                {
                    if (null == m)
                    {
                        m = DB.QizSubjectObjForDoctors.CreateObject();
                        m.ID = DB.NewID();
                        m.QizSubjectID = SubjectID;
                        m.RecuperID = uid;
                        m.DoctorID = SiteUser.UserId;
                        m.Timemark = DateTime.Now;
                        DB.QizSubjectObjForDoctors.AddObject(m);

                        inviteList.Add(m);
                    }
                    m.QizSmsSubjectID = SmsSubjSelection[i];
                    m.RecuperInvitMsg = m.QizSmsSubject.RecuperInvitMsg;
                }
                else
                {
                    if (null != m) DB.QizSubjectObjForDoctors.DeleteObject(m);
                }
            }
            DB.SaveChanges();
            Services.AddToSubjectNotify(inviteList);
            return Content("保存完成。");
        }
        public ActionResult SubjectRecuperList(string SubjectID, bool IsContain, ListViewModel<CommonSearchValues2, IQueryable<Recuper>> m = null)
        {
            if (string.IsNullOrEmpty(SubjectID)) throw new ArgumentException("必须选择随访。");

            ViewBag.SmsSubjects = DB.QizSmsSubjects.Where(v => v.SubjectID == SubjectID && v.QizSubject.DepID == SiteUser.DepartmentID && (v.DoctorID == SiteUser.UserId || SiteUser.IsDoctorDepManager));
            m = Services.SubjectRecuperListForDoctor(SubjectID, IsContain, m);
            return PartialView(m);

        }


        public ActionResult SubjectRecuperListExport(string ExportType, string SubjectID, bool IsContain, string CurrentFilterOfJson)
        {
            ListViewModel<CommonSearchValues2, IQueryable<Recuper>> m = Services.ParseListViewModeJsonFilterEx<CommonSearchValues2, Recuper>(CurrentFilterOfJson);
            var data = Services.SubjectRecuperListForDoctor(SubjectID, IsContain, m, true).Data;
            var subject = DB.QizSubjects.First(v => v.ID == SubjectID);

            string[] titles = "常规随访名称,备注说明,短信随访,随访姓名,患者编号,性别,出生日期,手机号,其它手机,家庭电话,家庭其它,其它电话,亲属其它,患者来源,身高,体重,证件类型,证件号,社保号,邮编,地址,电子邮箱,随访类型,主管医生,入院日期,出院日期,病案号,手术日期,出院诊断,采取手术,特殊医用耗材".Split(',');
            string fn = string.Format("{0}{1}常规随访患者信息导出", IsContain ? "参加" : "未参加", subject.Title);

            List<string[]> tempexportdata = null;
            #region set tempexportdata value
            tempexportdata = data.ToList().Select(v => new string[] {
                subject.Title,
                subject.DescForDoctor,
                IsContain?v.QizSubjectObjForDoctors.FirstOrDefault(t => t.QizSubjectID == SubjectID && (t.DoctorID == SiteUser.UserId)).QizSmsSubject.Title :string.Empty,
                v.User.UserName,
                v.RecuperID,
                v.User.Gender,
                v.User.BirthDay.ToString(DefaultDateFormat),
                v.User.MobileAlias,
                v.User.MobileAliasB,
                v.User.HomePhone,
                v.User.HomePhoneB,
                v.User.OtherPhone,
                v.User.OtherPhoneB,
                v.User.HuanZheLaiYuan,
                v.User.UserHeight,
                v.User.UserWeight,
                v.User.IDCodeType,
                v.User.IDCode,
                v.User.SheBaoHao,
                v.User.PostCode,
                v.User.Address,
                v.User.Email,
                v.SuiFangLeiXing,
                v.Doctor.UserName,
                v.EnHospDay.ToString(DefaultDateFormat),
                v.DeHospDay==DateTime.MinValue?string.Empty:v.DeHospDay.ToString(DefaultDateFormat),
                v.BingAnHao.ToString(),
                v.ZhuYuanYiSheng,
                v.ZhenDuanS,
                v.ShouShuS,
                v.BeiZhu
            }).ToList();
            #endregion
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            return File(WebUI.Services.DocumentServices.CreateSpreadsheetDocument(fn, titles, tempexportdata), "application/vnd.ms-excel", fn + ".xlsx");
        }


        //[HttpPost]
        public ActionResult RecuperList(ListViewModel<CommonSearchValues2, IQueryable<Recuper>> m = null)
        {
            m = Services.RecuperListForDoctor(m);
            return PartialView(m);

        }

        public ActionResult RecuperListExport(string ExportType, string CurrentFilterOfJson)
        {
            ListViewModel<CommonSearchValues2, IQueryable<Recuper>> m = Services.ParseListViewModeJsonFilterEx<CommonSearchValues2, Recuper>(CurrentFilterOfJson);
            var data = Services.RecuperListForDoctor(m, true).Data;
            string[] titles = "姓名,患者编号,性别,出生日期,手机号,其它手机,家庭电话,家庭其它,其它电话,亲属其它,患者来源,身高,体重,证件类型,证件号,社保号,邮编,地址,电子邮箱,随访类型,主管医生,入院日期,出院日期,病案号,手术日期,出院诊断,采取手术,特殊医用耗材".Split(',');
            string fn = "患者住院记录导出";

            List<string[]> tempexportdata = null;
            #region set tempexportdata value
            tempexportdata = data.ToList().Select(v => new string[] {
                    v.User.UserName,
                    v.RecuperID,
                    v.User.Gender,
                    v.User.BirthDay.ToString(DefaultDateFormat),
                    v.User.MobileAlias,
                    v.User.MobileAliasB,
                    v.User.HomePhone,
                    v.User.HomePhoneB,
                    v.User.OtherPhone,
                    v.User.OtherPhoneB,
                    v.User.HuanZheLaiYuan,
                    v.User.UserHeight,
                    v.User.UserWeight,
                    v.User.IDCodeType,
                    v.User.IDCode,
                    v.User.SheBaoHao,
                    v.User.PostCode,
                    v.User.Address,
                    v.User.Email,
                    v.SuiFangLeiXing,
                    v.Doctor==null?"":v.Doctor.UserName,
                    v.EnHospDay.ToString(DefaultDateFormat),
                    v.DeHospDay==DateTime.MinValue?string.Empty:v.DeHospDay.ToString(DefaultDateFormat),
                    v.BingAnHao.ToString(),
                    v.ZhuYuanYiSheng,
                    v.ZhenDuanS,
                    v.ShouShuS,
                    v.BeiZhu
                }).ToList();
            #endregion
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            return File(WebUI.Services.DocumentServices.CreateSpreadsheetDocument(fn, titles, tempexportdata), "application/vnd.ms-excel", fn + ".xlsx");
        }



        [HttpGet]
        public ActionResult QueryRecUser()
        {
            return PartialView();
        }
        [HttpPost]
        public ActionResult QueryRecUser(string Title, string MobileAlias, string Submit)
        {
            if (Submit == "录入")
            {
                return RedirectToAction("RecuperEdit", new { ID = Guid.Empty });
            }
            else
            {
                var q = DB.aspnet_Users.AsQueryable();
                if (!string.IsNullOrEmpty(Title)) q = q.Where(v => v.UserName == Title);
                if (!string.IsNullOrEmpty(MobileAlias)) q = q.Where(v => v.MobileAlias == MobileAlias);
                var qc = q.Count();
                if (qc > 1)
                {
                    throw new SiteException("输入的信息不明确，请重新输入。");
                }
                else if (qc < 1)
                {
                    throw new SiteException("对应的患者不存在，请重新输入查询或为其进行基本信息登记。");
                }
                else
                {
                    var u = q.First();
                    if (u.MainRoleName != "Recuper")
                    {
                        throw new SiteException("帐号已经被注册为其他角色，需要用不同的名称和手机号重新注册。。");
                    }
                    else
                    {
                        //var m = q.First().UserId;
                        return RedirectToAction("RecuperEdit", new { ID = q.First().UserId });
                    }
                }
            }

        }

        [OutputCache(Duration = 0)]
        public ActionResult RecuperEdit(Guid ID)
        {
            ViewBag.ReQizSubjects = SiteUser.Department.QizSubjects;
            var qsids = SiteUser.Department.QizSubjects.Select(v => v.ID);
            ViewBag.ReQizSmsSubjects = DB.QizSmsSubjects.Where(v => qsids.Contains(v.SubjectID));

            aspnet_Users m = null;
            if (ID == Guid.Empty)
            {
                m = new aspnet_Users();
            }
            else
            {
                m = DB.aspnet_Users.Where(v => v.UserId == ID).FirstOrDefault();
            }
            return PartialView(m);
        }

        ////[OutputCache(Duration = 0)]
        //public ActionResult RecuperEdit(Guid userid)
        //{
        //    //throw new NotImplementedException();
        //    //TODO: must edit this method. 
        //    // if specify ID,load this recuper to edit. 
        //    // if not specify the id, must set userid,and add a new recuper for this user.

        //    ViewBag.ReQizSubjects = SiteUser.Department.QizSubjects;
        //    var qsids = SiteUser.Department.QizSubjects.Select(v => v.ID);
        //    ViewBag.ReQizSmsSubjects = DB.QizSmsSubjects.Where(v => qsids.Contains(v.SubjectID));

        //    aspnet_Users m = null;
        //    if (string.IsNullOrEmpty(ID) && string.IsNullOrEmpty(userid))
        //    {
        //        m = new aspnet_Users();
        //        m.HospitalID = SiteUser.HospitalID;
        //        m.BingQuID = SiteUser.BingQuID;
        //        m.DepartmentID = SiteUser.DepartmentID; 
        //        m.Department = SiteUser.Department;


        //        //must has a user. or throw a error;
        //    }
        //    else
        //    {
        //        //m = DB.aspnet_Users.Where(v => v.re == ID).FirstOrDefault();
        //        m = DB.Recupers.FirstOrDefault(v => v.RecuperID == ID);
        //    }
        //    return PartialView(m);
        //}

        [HttpPost]
        [OutputCache(Duration = 0)]
        public ActionResult RecuperEdit(aspnet_Users m, string Pwd)
        {
            aspnet_Users tm = null;
            if (m.UserId == Guid.Empty)
            {
                if (string.IsNullOrEmpty(m.UserName))
                {
                    throw new SiteException("请输入用户名！");
                }

                if (string.IsNullOrEmpty(m.MobileAlias))
                {
                    throw new SiteException("请输入手机号！");
                }
                if (string.IsNullOrEmpty(m.Gender))
                {
                    throw new SiteException("请选择患者性别！");
                }
                if (m.BirthDay == DateTime.MinValue)
                {
                    throw new SiteException("请输入出生日期！");
                }
                var lun = m.UserName.ToLower();
                if (DB.aspnet_Users.Any(v => v.LoweredUserName == lun))
                {
                    throw new SiteException("用户名已经在使用！");
                }

                if (string.IsNullOrWhiteSpace(Pwd))
                {
                    Pwd = m.MobileAlias;
                }
                try
                {
                    var mu = Membership.CreateUser(m.UserName, Pwd);
                    if (null == mu)
                    {
                        ModelState.AddModelError("", new Exception("Error when create user."));
                        throw new SiteException("创建用户遇到未知以外。");
                    }
                    System.Web.Security.Roles.AddUserToRole(mu.UserName, "Recuper");

                    tm = DB.aspnet_Users.Where(v => v.UserName == m.UserName).FirstOrDefault();

                    m.LoweredUserName = m.UserName.ToLower();
                    m.MainRoleName = "Recuper";
                    m.UserId = tm.UserId;
                    m.ApplicationId = tm.ApplicationId;
                    m.LastActivityDate = tm.LastActivityDate;
                    DB.aspnet_Users.ApplyCurrentValues(m);

                    DB.SaveChanges();

                }
                catch (Exception ex)
                {
                    try
                    {
                        Membership.DeleteUser(m.UserName, true);
                    }
                    catch { }
                    throw new SiteException(ex.Message);
                }

            }
            else
            {
                if (string.IsNullOrEmpty(m.Gender))
                {
                    throw new SiteException("请选择患者性别！");
                }
                if (string.IsNullOrEmpty(m.MobileAlias))
                {
                    throw new SiteException("请输入手机号！");
                }
                if (m.BirthDay == DateTime.MinValue)
                {
                    throw new SiteException("请输入出生日期！");
                }
                tm = DB.aspnet_Users.Where(v => v.UserId == m.UserId).FirstOrDefault();
                tm.UserName = m.UserName;

                if (!string.IsNullOrEmpty(Pwd))
                {
                    var mu = Membership.GetUser(m.UserName);
                    string tp = mu.ResetPassword();
                    mu.ChangePassword(tp, Pwd);
                }

                m.LoweredUserName = m.UserName.ToLower();
                m.MainRoleName = "Recuper";
                m.UserId = tm.UserId;
                m.ApplicationId = tm.ApplicationId;
                m.LastActivityDate = tm.LastActivityDate;
                DB.aspnet_Users.ApplyCurrentValues(m);

                DB.SaveChanges();
            }


            //return RedirectToAction("RecuperList");
            return RedirectToAction("RecuperEdit", new { ID = m.UserId, _MsgBox = "保存成功。", _Flag = "A" });
        }

        public ActionResult RecuperDelete(string ID)
        {
            var m = DB.Recupers.Where(v => v.RecuperID == ID).FirstOrDefault();
            DB.Recupers.DeleteObject(m);
            DB.SaveChanges();
            if (DB.Recupers.Where(v => v.UserID == m.UserID).Count() == 0)
            {
                Membership.DeleteUser(m.User.UserName);
            }

            return RedirectToAction("RecuperList");
        }
        //public ActionResult ZhenDuanFenLei(string CV)
        public ActionResult ZhenDuanFenLei(string V1, string act)
        {
            ViewBag.Act = act;
            if (act == "search")
            {
                if (!string.IsNullOrEmpty(V1))
                {
                    return PartialView(DB.diag_sum_v2.Where(v => v.PinyinKey.Contains(V1) || v.Title.Contains(V1)));
                }
                return PartialView(new diag_sum_v2[0]);

            }
            else
            {
                return PartialView(null);
            }
        }

        public ActionResult BeiJianFenLei(string CV)
        {
            string[] cva = string.IsNullOrEmpty(CV) ? new string[0] : CV.Split(';');
            ViewBag.CV = cva;
            //return PartialView(DB.diag_sum.First(v => v.diag_code == "9999"));
            return PartialView(DB.diag_sum.First(v => v.Parent_Code == null && v.Pro_code == "BJ_" + SiteUser.BingQuID));
        }
        //public ActionResult ShouShuFenLei(string CV)
        public ActionResult ShouShuFenLei(string V1, string act)
        {
            //string[] cva = string.IsNullOrEmpty(CV) ? new string[0] : CV.Split(';');
            //ViewBag.CV = cva;
            //return PartialView(DB.surg_sum.First(v => v.surg_code == "000001"));

            ViewBag.Act = act;
            if (act == "search")
            {
                if (!string.IsNullOrEmpty(V1))
                {
                    return PartialView(DB.surg_sum_v2.Where(v => v.PinyinKey.Contains(V1) || v.Title.Contains(V1)));
                }
                return PartialView(new surg_sum_v2[0]);

            }
            else
            {
                return PartialView(null);
            }

        }

        [HttpGet]
        public ActionResult RecuperEnHospEdit(string ID, Guid? UserID)
        {
            Recuper m = null;
            if (string.IsNullOrEmpty(ID))
            {
                var user = DB.aspnet_Users.First(v => v.UserId == UserID);
                //create new by UserID
                m = new Recuper();
                m.UserID = UserID.Value; m.User = user;
                m.Hospital = SiteUser.Hospital; m.HospitalID = SiteUser.HospitalID;
                m.BingQu = SiteUser.BingQu; m.BingQuID = SiteUser.BingQuID;
                m.Department = SiteUser.Department; m.DepartmentID = SiteUser.DepartmentID;

            }
            else
            {
                //edit by ID
                m = DB.Recupers.FirstOrDefault(v => v.RecuperID == ID);
            }
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult RecuperEnHospEdit(Recuper om)
        {
            Recuper m = null;
            if (om.EnHospDay == DateTime.MinValue)
            {
                throw new SiteException("请选择入院日期！");
            }
            if (om.DoctorID == Guid.Empty)
            {
                throw new SiteException("请输入主管医生！");
            }
            else if (om.BingAnHao == 0)
            {
                throw new SiteException("请输入病案号！");
            }



            if (string.IsNullOrEmpty(om.RecuperID))
            {
                //如果是新建，检查是否在此deparment有过住院，如果有，备份就的，并更新新的成当前的。否则就是新建住院
                //本质上是 继承就的ID，以保证以前的引用都正常，旧的用另一个ID，只是记录作用了。
                //2013-12-31；不需要以上逻辑了。各是各的。
                var user = DB.aspnet_Users.First(v => v.UserId == om.UserID);
                //var oldrec = user.UserAllRecupers.FirstOrDefault(v => v.DepartmentID == SiteUser.DepartmentID && v.GuoQi == false);
                //if (null != oldrec)
                //{
                //    if (om.EnHospDay == DateTime.MinValue)
                //    {
                //        throw new SiteException("请选择入院日期！");
                //    }
                //    if (om.DoctorID == Guid.Empty)
                //    {
                //        throw new SiteException("请输入主治医生！");
                //    }
                //    else if (om.BingAnHao == 0)
                //    {
                //        throw new SiteException("请输入病案号！");
                //    }
                //    var orecid = oldrec.RecuperID;
                //    DB.Recupers.Detach(oldrec);
                //    oldrec.RecuperID = DB.NewID();
                //    oldrec.GuoQi = true;
                //    DB.Recupers.AddObject(oldrec);

                //    om.RecuperID = orecid;//oldrec.RecuperID;
                //    DB.Recupers.Where(v => v.RecuperID == orecid).First();
                //    //DB.Recupers.AddObject(om);
                //    DB.Recupers.ApplyCurrentValues(om);
                //    m = om;//om;

                //}
                //else
                //{
                om.RecuperID = DB.NewID();
                DB.Recupers.AddObject(om);
                m = om;
                //}
            }
            else
            {
                m = DB.Recupers.First(v => v.RecuperID == om.RecuperID);
                DB.Recupers.ApplyCurrentValues(om);
                if (m.GuoQi)
                {
                    var ofd = m.QizSubjectObjForDoctors.ToList();
                    foreach (var item in ofd)
                    {
                        DB.QizSubjectObjForDoctors.DeleteObject(item);
                    }
                }

                m = om;
            }

            m.SuiFangLeiXing = Services.DepartmentProfileSettingArrayEditor("SuiFangLeiXing", m.SuiFangLeiXing);
            //更新定制属性
            Services.UpdateRecuperAttachInfo(om);

            DB.SaveChanges();
            return RedirectToAction("RecuperEnHospEdit", new { ID = m.RecuperID, _MsgBox = "保存成功。可以继续修改或关闭。" });
        }
        ///////////////////////////////////短信随访

        public ActionResult SmsQuizMgr()
        {
            return View();
        }
        public ActionResult SmsQuizList()
        {
            //var m = DB.QizSmsSubjects.Where(v => v.DoctorID == SiteUser.UserId || (SiteUser.Recuper != null && SiteUser.Recuper.QizSmsSubjectID == v.ID));
            var m = DB.QizSubjects.Where(v => v.DepID == SiteUser.DepartmentID);
            return PartialView(m);
        }

        public ActionResult SmsQuizDetail(string ID)
        {
            var m = DB.QizSmsSubjects.Where(v => v.ID == ID && (SiteUser.IsDoctorDepManager || v.DoctorID == SiteUser.UserId)).FirstOrDefault();
            return PartialView(m);
        }


        [HttpGet]
        public ActionResult SmsQuizEdit(string ID, string MonthIdxID)
        {

            QizSmsSubject m = null;
            ViewBag.Subjects = DB.QizSubjects.Where(v => v.DepID == SiteUser.DepartmentID).OrderByDescending(v => v.SortIdx);
            if (string.IsNullOrEmpty(ID)) m = new QizSmsSubject() { };
            else
            {
                m = DB.QizSmsSubjects.Where(v => v.ID == ID && (SiteUser.IsDoctorDepManager || v.DoctorID == SiteUser.UserId)).First();

                //QizSmsSubjectMonthIdx m2 = null;
                //if (!string.IsNullOrEmpty(MonthIdxID)) m2 = new QizSmsSubjectMonthIdx() { QizSmsSubject = m };
                //else m2 = DB.QizSmsSubjectMonthIdxes.Where(v => v.ID == MonthIdxID).First();
                //ViewBag.MonthIdx = m2;
            }
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SmsQuizEdit(QizSmsSubject m)
        {
            bool needUpdateMonthIdx = false;
            if (string.IsNullOrEmpty(m.ID))
            {
                m.ID = DB.NewID();
                needUpdateMonthIdx = true;
                m.DoctorID = SiteUser.UserId;
                DB.QizSmsSubjects.AddObject(m);

            }
            else
            {
                var om = DB.QizSmsSubjects.Where(v => v.ID == m.ID && (SiteUser.IsDoctorDepManager || v.DoctorID == SiteUser.UserId)).First();
                needUpdateMonthIdx = (om.MonthIdxListStr == m.MonthIdxListStr);
                DB.QizSmsSubjects.ApplyCurrentValues(m);

            }



            DB.SaveChanges();
            return RedirectToAction("SmsQuizList");
        }

        public ActionResult SmsQuizDel(string ID)
        {
            var m = DB.QizSmsSubjects.Where(v => v.ID == ID && (SiteUser.IsDoctorDepManager || v.DoctorID == SiteUser.UserId)).First();
            DB.QizSmsSubjects.DeleteObject(m);
            DB.SaveChanges();
            return RedirectToAction("SmsQuizList");
        }
        [HttpGet]
        public ActionResult SmsQuizMonthIdxEdit(string ID, string SmsSubjectID)
        {
            QizSmsSubjectMonthIdx m = null;
            var rootcata = DB.Catalogs.First(v => v.CatalogID == "02001");
            ViewBag.RootCata = rootcata;
            if (string.IsNullOrEmpty(ID))
            {
                var qizSmsSubject = DB.QizSmsSubjects.First(v => v.ID == SmsSubjectID);


                m = new QizSmsSubjectMonthIdx() { MonthIdx = 0, SmsSendingMonthIdx = 2, SmsSendingDayIdx = 15, QizSmsSubject = qizSmsSubject };
            }
            else
            {
                m = DB.QizSmsSubjectMonthIdxes.Where(v => v.ID == ID).First();
            }
            return PartialView(m);
        }
        [HttpPost]
        public ActionResult SmsQuizMonthIdxEdit(QizSmsSubjectMonthIdx m, string IDS, string[] Selection)
        {
            QizSmsSubjectMonthIdx nm = null;
            if (m.MonthIdx == 0)
            {
                throw new ArgumentException("输入的月不正确。");
            }

            if (string.IsNullOrEmpty(m.ID))
            {
                m.ID = DB.NewID();

                int midx = m.MonthIdx;

                //var lastmonidx = 0;
                //var q = DB.QizSmsSubjectMonthIdxes.Where(v => v.MonthIdx < midx&&v.QizSmsSubjectID==m.QizSmsSubjectID);
                //if (q.Count() > 0)lastmonidx = q.Max(v => v.MonthIdx);

                //var nextmon = DB.QizSmsSubjectMonthIdxes.FirstOrDefault(v => v.LastMonthIdx == lastmonidx);
                //if (null != nextmon) nextmon.LastMonthIdx = midx;
                //m.LastMonthIdx = lastmonidx;

                DB.QizSmsSubjectMonthIdxes.AddObject(m);
            }
            else
            {
                DB.QizSmsSubjectMonthIdxes.Where(v => v.ID == m.ID).First();
                DB.QizSmsSubjectMonthIdxes.ApplyCurrentValues(m);
            }
            //重新计算 lastmonidx
            var templmidx = 0;
            foreach (var mi in DB.QizSmsSubjectMonthIdxes.Where(v => v.QizSmsSubjectID == m.QizSmsSubjectID).OrderBy(v => v.MonthIdx))
            {
                if (mi.LastMonthIdx != templmidx) mi.LastMonthIdx = templmidx;
                templmidx = mi.MonthIdx;
            }

            DB.SaveChanges();



            nm = DB.QizSmsSubjectMonthIdxes.Where(v => v.ID == m.ID).First();
            var SsdSelection = nm.QizSmsSubject.QizSubject.QizSubjectDefines.Where(v => Selection.Contains(v.QizItemID)).Select(v => v.ID).ToList();
            foreach (var item in nm.QizSmsSubject.QizSubject.SubQizSubjects)
            {
                SsdSelection.AddRange(item.QizSubjectDefines.Where(v => Selection.Contains(v.QizItemID)).Select(v => v.ID).ToList());
            }

            var cur = nm.QizSmsSubjDefines.Select(v => v.QizSubjDefID);
            var added = SsdSelection.Except(cur);
            var deled = cur.Except(SsdSelection);

            //var removeItem = nm.QizSmsSubjDefines.Where(v => deled.Contains(v.QizSubjDefID));
            //foreach (var item in removeItem)
            //{
            //    nm.QizSmsSubjDefines.Remove(item);
            //}
            foreach (var item in DB.QizSubjectDefines.Where(v => added.Contains(v.ID)))
            {
                if (nm.QizSmsSubjDefines.Count > 10) break;
                nm.QizSmsSubjDefines.Add(new QizSmsSubjDefine() { ID = DB.NewID(), QizSmsSubjectMonthIdx = nm, QizSubjectDefine = item });

            }

            var qizReminding = DB.QizSessionRemindings.FirstOrDefault(s => s.QizSmsMonthIdxID == m.ID && s.TaskType == "随访");
            if (qizReminding == null)
            {
                qizReminding = new QizSessionReminding()
                {
                    ID = DB.NewID(),
                    QizSmsMonthIdxID = m.ID,
                    MonthOffset = m.SmsSendingMonthIdx,
                    DayOffset = m.SmsSendingDayIdx,
                    TaskType = "随访",
                    TaskEnabled = "启用"
                };
                DB.QizSessionRemindings.AddObject(qizReminding);
            }
            DB.SaveChanges();
            return RedirectToAction("SmsQuizDetail", new { ID = nm.QizSmsSubjectID });
        }

        public ActionResult SmsQuizDefineDel(string ID)
        {
            var m = DB.QizSmsSubjDefines.Where(v => v.ID == ID).First();
            DB.QizSmsSubjDefines.DeleteObject(m);
            var mi = DB.QizSmsSubjectMonthIdxes.Where(v => v.ID == m.QizSmsSubjMonthIdxID).First();
            DB.SaveChanges();
            return RedirectToAction("SmsQuizDetail", new { ID = mi.QizSmsSubjectID });
        }

        public ActionResult SmsQuizMonthIdxDel(string ID)
        {
            var m = DB.QizSmsSubjectMonthIdxes.Where(v => v.ID == ID).First();
            DB.DeleteAll(m.QizSessionRemindings.ToArray());
            DB.QizSmsSubjectMonthIdxes.DeleteObject(m);
            DB.SaveChanges();
            return RedirectToAction("SmsQuizDetail", new { ID = m.QizSmsSubjectID });
        }



        ///////////////////SMS

        public ActionResult SentSms(ListViewModel<CommonSearchValues, IQueryable<SmsSent>> m = null)
        {
            if (null == m || m.SearchFrom == null)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<SmsSent>>()
                {
                    PageSize = Services.DefaultPageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            List<string> doctors = new List<string>();
            if (SiteUser.IsDoctorDepManager)
            {
                doctors = DB.Doctors.Where(s => s.DepartmentID == SiteUser.DepartmentID).Select(s => s.UserId.ToString()).ToList();
            }
            else
            {
                var uid = SiteUser.UserId.ToString();
                doctors.Add(uid);
            }

            var d = DB.SmsSents.Where(v => doctors.Contains(v.SenderCode));
            ViewBag.Recupers = d.Select(v => v.ReceiverName).Distinct();
            //ViewBag.Subjects = SiteUser.IsDoctorDepManager ? DB.QizSubjects.Where(q => q.DepID == SiteUser.DepartmentID) : DB.QizSubjects.Where(q => q.QizSubjectObjForDoctors.Any(s => s.DoctorID == SiteUser.UserId));
            ViewBag.SmsTypes = DB.SmsSents.Where(s => s.SmsType != string.Empty && s.SmsType != null).Select(s => s.SmsType).Distinct();

            //if (User.IsInRole("Admin") || User.IsInRole("Engineer")) { ;}
            //else if (User.IsInRole("Doctor")) { var o = SiteUser.UserId.ToString(); d = d.Where(v => v.ReceiverCode == o); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { var w = DateTime.Parse(m.SearchFrom.V1); d = d.Where(v => v.SentTime >= w); }
            if (!string.IsNullOrEmpty(m.SearchTo.V1)) { var w = DateTime.Parse(m.SearchTo.V1).AddDays(1); d = d.Where(v => v.SentTime <= w); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V3) && m.SearchFrom.V3 != "全部")
            {
                var smsType = m.SearchFrom.V3;
                d = d.Where(v => v.SmsType == smsType);
                //var tempRecupers = DB.QizSubjectRecupers.Where(s => s.QizSubjectID == m.SearchFrom.V3).Select(v => v.Recuper.User.UserName).Distinct();
                //d = d.Where(v => tempRecupers.Contains(v.ReceiverName));
            }
            if (!string.IsNullOrEmpty(m.SearchFrom.V2) && m.SearchFrom.V2 != "全部") { d = d.Where(v => v.ReceiverName.Contains(m.SearchFrom.V2)); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V4)) { d = d.Where(v => v.ReceiverCode == m.SearchFrom.V4); }
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)m.ItemCount / m.PageSize);
            d = d.OrderByDescending(v => v.SentTime);
            m.Data = d.Skip(m.PageSize * m.PageIdx).Take(m.PageSize);
            //m.Data = d;
            return ViewOrPartial(m);
        }

        public ActionResult SentSmsEdit(string[] recivers, string txtmessage)
        {
            if (recivers == null)
            {
                ViewBag.Templates = DB.SmsTemplates.Where(v => v.Type == "短信留言" && v.DoctorID == SiteUser.UserId);
                ViewBag.Recupers = null;// DB.Recupers.Where(v => v.DoctorID == SiteUser.UserId);
                return ViewOrPartial(null);
            }
            else
            {
                if (recivers.Length == 0 || string.IsNullOrEmpty(txtmessage)) { throw new SiteException("必须选择收件人且短信内容不能为空白。"); }
                foreach (var item in recivers.Distinct())
                {
                    Guid uid = Guid.Empty;
                    if (!Guid.TryParse(item, out uid)) continue;
                    var r = DB.aspnet_Users.Where(v => v.UserId == uid).FirstOrDefault();
                    if (null != r)
                    {
                        DB.SmsSents.AddObject(new SmsSent()
                        {
                            ID = DB.NewID(),
                            ReceiverCode = r.MobileAlias,
                            SenderCode = SiteUser.UserId.ToString(),
                            ReceiverName = r.UserName,
                            SenderName = SiteUser.UserName,
                            TextMessage = txtmessage,
                            SentTime = DateTime.Now,
                            ProcStatus = "发送",
                            SmsType = "医生留言"

                        });
                    }

                }
                DB.SaveChanges();
                //return RedirectToAction("SentSms", new { IsView = false });
                return Content("OK");
            }

        }

        public ActionResult SentSmsToSessionRecuper(string reciver, string txtmessage)
        {
            if (txtmessage == null)
            {
                ViewBag.Templates = DB.SmsTemplates.Where(v => v.Type == "短信留言" && v.DoctorID == SiteUser.UserId);
                var user = DB.Recupers.FirstOrDefault(s => s.RecuperID == reciver);
                return PartialView(user);
            }
            else
            {
                if (reciver.Length == 0 || string.IsNullOrEmpty(txtmessage)) { throw new SiteException("必须选择收件人且短信内容不能为空白。"); }

                var r = DB.Recupers.Where(v => v.RecuperID == reciver).FirstOrDefault().User;
                if (null != r)
                {
                    DB.SmsSents.AddObject(new SmsSent()
                    {
                        ID = DB.NewID(),
                        ReceiverCode = r.MobileAlias,
                        SenderCode = SiteUser.UserId.ToString(),
                        ReceiverName = r.UserName,
                        SenderName = SiteUser.UserName,
                        TextMessage = txtmessage,
                        SentTime = DateTime.Now,
                        ProcStatus = "发送",
                        SmsType = "医生留言"

                    });
                }
                DB.SaveChanges();
                return RedirectToAction("SFDList");
                //return RedirectToAction("SentSms", new { IsView = false });
            }

        }

        public ActionResult SentSmsImportRecuper(string submit, Guid[] SIDS, Guid[] Selection, ListViewModel<CommonSearchValues, IQueryable<Recuper>> m = null)
        {
            if (submit == "添加")
            {
                List<Guid> sids = new List<Guid>();
                foreach (var s in Selection)
                {
                    sids.Add(s);
                }
                //return RedirectToAction("SentSmsEdit", new {RecuperList=DB.Recupers.Where(v => sids.Contains(v.UserID))});

                //ViewBag.RecuperUsers = DB.Recupers.Where(v => sids.Contains(v.UserID)).Select(v=>v.User).Distinct();
                ViewBag.RecuperUsers = DB.aspnet_Users.Where(v => sids.Contains(v.UserId)).Distinct();
                return PartialView("SentSmsEdit", null);
            }
            else
            {
                //IQueryable<Recuper> 
                //var d = DB.QizSubjectObjForDoctors.Where(v => v.DoctorID == SiteUser.UserId);//.Select(v => v.Recuper);
                var d = DB.QizSubjectObjForDoctors.Where(v => v.Doctor.DepartmentID == SiteUser.DepartmentID);//.Select(v => v.Recuper);
                if (m != null && m.SearchFrom != null)
                {
                    if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { d = d.Where(v => v.QizSubjectID == m.SearchFrom.V1); }
                    if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { d = d.Where(v => v.Recuper.ShouShuS.Contains(m.SearchFrom.V2)); }
                    if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { d = d.Where(v => v.Recuper.ZhenDuanS.Contains(m.SearchFrom.V3)); }
                    if (!string.IsNullOrEmpty(m.SearchFrom.V4)) { var o = DateTime.Parse(m.SearchFrom.V4); d = d.Where(v => v.Recuper.DeHospDay >= o); }
                    if (!string.IsNullOrEmpty(m.SearchTo.V4)) { var o = DateTime.Parse(m.SearchTo.V4); d = d.Where(v => v.Recuper.DeHospDay <= o); }
                    if (!string.IsNullOrEmpty(m.SearchFrom.V5)) { d = d.Where(v => v.Recuper.SuiFangLeiXing.Contains(m.SearchFrom.V5)); }
                    if (!string.IsNullOrEmpty(m.SearchFrom.V0)) { d = d.Where(v => v.Recuper.User.UserName.Contains(m.SearchFrom.V0)); }
                    if (!string.IsNullOrEmpty(m.SearchFrom.V6) && m.SearchFrom.V6 != "全部")
                    {
                        Guid v6 = Guid.Parse(m.SearchFrom.V6);
                        d = d.Where(v => v.Recuper.Doctor.UserId == v6);
                    }
                }
                else
                {
                    m = new ListViewModel<CommonSearchValues, IQueryable<Recuper>>()
                    {
                        SearchFrom = new CommonSearchValues()
                        ,
                        SearchTo = new CommonSearchValues()
                    };
                }
                ViewBag.Subjects = DB.QizSubjectObjForDoctors.Where(v => v.DoctorID == SiteUser.UserId).Select(v => v.QizSubject).Distinct();
                m.Data = d.Select(v => v.Recuper).Distinct();
                return PartialView(m);
            }

        }

        public ActionResult RecuperReport1(string QizSmsSubjectID, string UserID, int MonthIdx = 0)
        {

            //var uid = string.IsNullOrEmpty(UserID) ? Guid.Empty : Guid.Parse(UserID);
            var uid = UserID;

            var recu = DB.Recupers.FirstOrDefault(v => v.RecuperID == uid);
            ViewBag.SmsSubjects = DB.QizSubjectObjForDoctors.Where(v => v.DoctorID == SiteUser.UserId).Select(v => v.QizSmsSubject).Distinct();
            ViewBag.UserIDs = DB.Recupers.Where(s => s.DepartmentID == SiteUser.DepartmentID).Select(v => v.User).Distinct(); //DB.QizSubjectObjForDoctors.Where(v=>v.DoctorID==SiteUser.UserId).Select(v => v.Recuper.User).Distinct();

            ViewBag.SmsSubjectID = QizSmsSubjectID;
            ViewBag.UserID = uid;

            var recuperSubject = DB.QizSubjectObjForDoctors.FirstOrDefault(s => s.RecuperID == uid && s.QizSmsSubjectID == QizSmsSubjectID);
            if (recuperSubject == null)
            {
                ViewBag.IsAttend = false;
                return ViewOrPartial(null);
            }
            ViewBag.IsAttend = true;
            if (MonthIdx == 0)
            {
                return ViewOrPartial(Services.RecuperSummaryReport(new string[] { uid }, MonthIdx, QizSmsSubjectID));
            }
            else
            {
                return ViewOrPartial(Services.RecuperSummaryReportOfMonthIdx(new string[] { uid }, MonthIdx, QizSmsSubjectID), "RecuperReportMonth");
            }
            //return ViewOrPartial(Services.RecuperSummaryReport(uid, MonthIdx, QizSmsSubjectID), MonthIdx == 0 ? null : "RecuperReportMonth");
        }

        public ActionResult RecuperReport(string qizSubjectID, string recuperID, string RecuperName, string EnHospDay, int pidx = 0)
        {
            var pageIndex = pidx;
            int pageSize = 10;
            //if (string.IsNullOrEmpty(qizSubjectID))
            //{
            //    qizSubjectID = DB.QizSubjectObjForDoctors.FirstOrDefault(s => s.Doctor.UserId == SiteUser.UserId).QizSubjectID;
            //}
            //if (string.IsNullOrEmpty(recuperID))
            //{
            //    recuperID = DB.Recupers.FirstOrDefault(s => s.QizSubjectObjForDoctors.Any(v => v.DoctorID == SiteUser.UserId)).RecuperID;
            //}
            ViewBag.Subjects = DB.QizSubjectObjForDoctors.Where(s => s.Doctor.UserId == SiteUser.UserId).Select(s => s.QizSubject).Distinct();
            //ViewBag.UserIDs = DB.Recupers.Where(s => s.QizSubjectObjForDoctors.Any(v => v.DoctorID == SiteUser.UserId)).Distinct();
            //var rids=DB.Recupers.Where(v=>v.User.UserName==RecuperName).Select(v=>v.RecuperID).ToArray();
            //var sessionsxxx=DB.QizSessions.Where(v => rids.Contains(v.RecuperID) && v.QizSubjectID == qizSubjectID);

            ViewBag.suifangs = null;
            if (string.IsNullOrEmpty(recuperID))
            {
                var suifangs = DB.QizSubjectObjForDoctors.Where(v => v.DoctorID == SiteUser.UserId && v.QizSubjectID == qizSubjectID && v.Recuper.User.UserName == RecuperName).ToList();
                if (suifangs.Count() > 1)
                {
                    ViewBag.suifangs = DB.QizSubjectObjForDoctors.Where(v => v.DoctorID == SiteUser.UserId && v.QizSubjectID == qizSubjectID && v.Recuper.User.UserName == RecuperName);

                    //一条以上
                    ViewBag.Recupers = suifangs.Select(v => v.Recuper);
                    recuperID = suifangs[0].RecuperID;
                    if (!string.IsNullOrEmpty(EnHospDay))
                    {
                        Recuper Recupers = suifangs.Select(v => v.Recuper).Where(c => c.EnHospDay == Convert.ToDateTime(EnHospDay)).FirstOrDefault();
                        recuperID = Recupers.RecuperID;
                    }
                }
                if (suifangs.Count() == 1)
                {


                    ViewBag.suifangs = DB.QizSubjectObjForDoctors.Where(v => v.DoctorID == SiteUser.UserId && v.QizSubjectID == qizSubjectID && v.Recuper.User.UserName == RecuperName);
                    //ViewBag.Recupers = suifangs.Select(v => v.Recuper);
                    recuperID = suifangs[0].RecuperID;


                }

            }

            var recu = DB.Recupers.FirstOrDefault(v => recuperID == v.RecuperID);
            ViewBag.Recuper = recu; ;
            var subj = DB.QizSubjects.FirstOrDefault(v => v.ID == qizSubjectID);
            ViewBag.Subject = subj;
            ViewBag.RecuperID = recuperID;

            if (recu == null || subj == null)
            {
                return ViewOrPartial(null);
            }

            List<QizSession> allSession = new List<QizSession>();

            var sessions = DB.QizSessions.AsQueryable();
            var smsSessions = DB.QizSmsSessions.Where(v => v.SessionStatus == 3);

            if (!string.IsNullOrEmpty(recuperID))
            {
                sessions = sessions.Where(v => v.RecuperID == recuperID);
                smsSessions = smsSessions.Where(v => v.RecuperID == recuperID);
            }
            if (!string.IsNullOrEmpty(qizSubjectID))
            {
                sessions = sessions.Where(v => v.QizSubjectID == qizSubjectID);
                smsSessions = smsSessions.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.SubjectID == qizSubjectID);
            }

            foreach (var session in sessions)
            {
                allSession.Add(session);
            }

            foreach (var session in smsSessions)
            {
                QizSession smsSession = new QizSession();
                smsSession.ID = DB.NewID();
                smsSession.Timemark = session.Timemark;
                smsSession.Recuper = session.Recuper;
                smsSession.QizSubject = session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject;
                smsSession.QizSubjectID = session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.ID;
                //smsSession.QizSessionDetails = new System.Data.Objects.DataClasses.EntityCollection<QizSessionDetail>();
                smsSession.SubmitSrc = "短信";
                foreach (var detail in session.QizSmsSessionDetails)
                {
                    QizSessionDetail qizDetail = new QizSessionDetail();
                    qizDetail.ID = DB.NewID();
                    qizDetail.QizSessionID = smsSession.ID;
                    qizDetail.QizSubjectDefID = detail.QizSmsSubjDefine.QizSubjDefID;
                    qizDetail.QizSubjectDefine = detail.QizSmsSubjDefine.QizSubjectDefine;
                    qizDetail.UserValue = detail.UserValue;
                    qizDetail.UserSelValue = "-1";
                    qizDetail.ValueAutoEvaluation = detail.ValueAutoEvalution;

                    smsSession.QizSessionDetails.Add(qizDetail);
                }
                allSession.Add(smsSession);
            }
            allSession = allSession.OrderBy(s => s.Timemark).ToList();
            ViewBag.StartTime = allSession.Count > 0 ? allSession.First().Timemark.ToString("yyyy-MM-dd HH:mm") : string.Empty;

            ViewBag.PageCount = (int)Math.Ceiling((double)allSession.Count() / pageSize);
            if (pageIndex < 0) pageIndex = 0;
            //pageIndex = pageIndex > 0 ? pageIndex - 1 : 0;
            ViewBag.PageIdx = pageIndex;

            return ViewOrPartial(allSession.Skip(pageIndex * pageSize).Take(pageSize).ToList());

        }

        public ActionResult SFReport()
        {
            ViewBag.SubjectCount = DB.QizSubjectObjForDoctors.Where(s => s.DoctorID == SiteUser.UserId).Select(s => s.QizSubjectID).Distinct().Count();
            ViewBag.ExcpectRecuperCount = DB.QizSubjectObjForDoctors.Where(s => s.DoctorID == SiteUser.UserId).Select(s => s.Recuper.RecuperID).Distinct().Count();
            ViewBag.ActualRecuperCount = DB.QizSessions.Where(s => s.QizSubject.QizSubjectObjForDoctors.Any(v => v.DoctorID == SiteUser.UserId)).Select(s => s.RecuperID).Distinct().Count();
            ViewBag.TotalSubmitCount = DB.QizSessions.Where(s => s.QizSubject.QizSubjectObjForDoctors.Any(v => v.DoctorID == SiteUser.UserId)).Count();


            //var m = DB.Hospitals_Fixed;
            return PartialView(null);
        }
        public ActionResult SmsSFReport()
        {
            ViewBag.SubjectCount = DB.QizSubjectObjForDoctors.Where(s => s.DoctorID == SiteUser.UserId).Select(s => s.QizSmsSubjectID).Distinct().Count();
            ViewBag.ExcpectRecuperCount = DB.QizSubjectObjForDoctors.Where(s => s.DoctorID == SiteUser.UserId).Select(s => s.RecuperID).Distinct().Count();
            ViewBag.ActualRecuperCount = DB.QizSmsSessions.Where(v => v.SessionStatus == 3).Where(s => s.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubjectObjForDoctors.Any(v => v.DoctorID == SiteUser.UserId)).Select(s => s.RecuperID).Distinct().Count();
            ViewBag.TotalSubmitCount = DB.QizSmsSessions.Where(v => v.SessionStatus == 3).Where(v => v.SessionStatus == 3).Where(s => s.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubjectObjForDoctors.Any(v => v.DoctorID == SiteUser.UserId)).Count();


            //var m = DB.Hospitals_Fixed;
            return PartialView(null);
        }
        ////////////////////////////患者信息

        public ActionResult SmsTemplateMgr()
        {
            return View();
        }

        public ActionResult SmsTemplateList(string smsType)
        {
            if (string.IsNullOrWhiteSpace(smsType))
            {
                var tempaltes = DB.SmsTemplates.Where(s => s.DoctorID == SiteUser.UserId);
                return PartialView(tempaltes);
            }
            else
            {
                var tempaltes = DB.SmsTemplates.Where(s => s.DoctorID == SiteUser.UserId && s.Type == smsType);
                return PartialView(tempaltes);
            }
        }

        [HttpGet]
        public ActionResult SmsTemplateEdit(string id)
        {
            if (string.IsNullOrEmpty(id)) return PartialView();
            else return PartialView(DB.SmsTemplates.Where(s => s.ID == id).FirstOrDefault());
        }

        [HttpPost]
        public ActionResult SmsTemplateEdit(SmsTemplate m)
        {
            var t = DB.SmsTemplates.Where(s => s.ID == m.ID && s.DoctorID == SiteUser.UserId).FirstOrDefault();
            if (t == null)
            {
                t = new SmsTemplate()
                {
                    ID = DB.NewID(),
                    Type = m.Type,
                    SmsText = m.SmsText,
                    DoctorID = SiteUser.UserId,
                    DepartmentID = SiteUser.DepartmentID
                };
                DB.SmsTemplates.AddObject(t);
            }
            else
            {
                t.Type = m.Type;
                t.SmsText = m.SmsText;
            }
            DB.SaveChanges();
            return RedirectToAction("SmsTemplateList");
        }

        public ActionResult SmsTemplateDelete(string id)
        {
            var t = DB.SmsTemplates.Where(s => s.ID == id && s.DoctorID == SiteUser.UserId).FirstOrDefault();
            if (t != null)
            {
                DB.SmsTemplates.DeleteObject(t);
                DB.SaveChanges();
            }
            return RedirectToAction("SmsTemplateList");
        }

        public ActionResult ImportSmsTemplate(string type)
        {
            var tempaltes = DB.SmsTemplates.Where(t => t.DoctorID == SiteUser.UserId && t.Type == type);
            ViewBag.Templates = tempaltes;
            return PartialView();
            //return PartialView(tempaltes); 
        }

        [HttpGet]
        public ActionResult QizSessionReminding(string id)
        {
            var qiz = DB.QizSmsSubjectMonthIdxes.Where(s => s.ID == id).FirstOrDefault();
            ViewBag.SmsSubIndexID = qiz.ID;
            ViewBag.QizSmsSubjectID = qiz.QizSmsSubjectID;
            ViewBag.MonthIndex = qiz.MonthIdx;
            ViewBag.SmsSendingMonthIdx = qiz.SmsSendingMonthIdx;
            ViewBag.SmsSendingDayIdx = qiz.SmsSendingDayIdx;
            var temp = DB.QizSessionRemindings.Where(s => s.QizSmsMonthIdxID == id && s.TaskType == "催报");
            if (temp.Count() == 0)
            {
                var item1 = new QizSessionReminding() { QizSmsMonthIdxID = id, ID = DB.NewID(), TaskEnabled = "未启用", TaskType = "催报", DayOffset = 1, MonthOffset = 1 };
                var item2 = new QizSessionReminding() { QizSmsMonthIdxID = id, ID = DB.NewID(), TaskEnabled = "未启用", TaskType = "催报", DayOffset = 1, MonthOffset = 1 };
                var item3 = new QizSessionReminding() { QizSmsMonthIdxID = id, ID = DB.NewID(), TaskEnabled = "未启用", TaskType = "催报", DayOffset = 1, MonthOffset = 1 };
                DB.QizSessionRemindings.AddObject(item1);
                DB.QizSessionRemindings.AddObject(item2);
                DB.QizSessionRemindings.AddObject(item3);
                DB.SaveChanges();
                List<QizSessionReminding> m = new List<QizSessionReminding> { item1, item2, item3 };
                return PartialView(m);
            }
            else
            {
                return PartialView(temp.ToList());
            }
        }

        [HttpPost]
        public ActionResult QizSessionReminding(string indexId, string[] isChecked, string[] RemindingID, string[] monthOffset, string[] dayOffset, string[] textContent)
        {
            if (isChecked == null) isChecked = new string[] { };
            var l = DB.QizSessionRemindings.Where(s => s.QizSmsMonthIdxID == indexId).ToList();
            for (int i = 0; i < 3; i++)
            {
                string id = RemindingID[i];
                var newReminding = DB.QizSessionRemindings.FirstOrDefault(s => s.ID == id);
                if (newReminding == null)
                {
                    newReminding = new QizSessionReminding();
                    newReminding.ID = DB.NewID();
                    newReminding.QizSmsMonthIdxID = indexId;
                    newReminding.MonthOffset = string.IsNullOrWhiteSpace(monthOffset[i]) ? 0 : int.Parse(monthOffset[i]);
                    newReminding.DayOffset = string.IsNullOrWhiteSpace(dayOffset[i]) ? 0 : int.Parse(dayOffset[i]);
                    newReminding.TextContent = textContent[i];
                    newReminding.TaskEnabled = isChecked.Contains(i.ToString()) ? "启用" : "未启用";
                    newReminding.TaskType = "催报";
                    DB.QizSessionRemindings.AddObject(newReminding);
                }
                newReminding.MonthOffset = string.IsNullOrWhiteSpace(monthOffset[i]) ? 0 : int.Parse(monthOffset[i]);
                newReminding.DayOffset = string.IsNullOrWhiteSpace(dayOffset[i]) ? 0 : int.Parse(dayOffset[i]);
                newReminding.TextContent = textContent[i];
                newReminding.TaskEnabled = isChecked.Contains(i.ToString()) ? "启用" : "未启用";
            }
            DB.SaveChanges();
            return RedirectToAction("SmsTemplateMgr");
        }

        public ActionResult SetQizSessionReaded(string ID)
        {
            var m = DB.QizSessions.FirstOrDefault(v => v.ID == ID);
            if (null == m) throw new SiteException("更新数据时发生错误，数据不存在。");
            m.UnRead = false;
            DB.SaveChanges();
            return Content(string.Empty);
        }
        public ActionResult SetQizSmsSessionReaded(string ID)
        {
            var m = DB.QizSmsSessions.FirstOrDefault(v => v.ID == ID);
            if (null == m) throw new SiteException("更新数据时发生错误，数据不存在。");
            m.UnRead = false;
            DB.SaveChanges();
            return Content(string.Empty);
        }

        [HttpGet]
        public ActionResult BLStartView(string RecuperID)
        {
            var recuper = DB.Recupers.FirstOrDefault(s => s.RecuperID == RecuperID);
            var subs = DB.QizSubjectObjForDoctors.Where(v => v.RecuperID == RecuperID).Select(v => v.QizSubject).Distinct();
            return PartialView(subs);
        }


        public ActionResult UserMemoList(ListViewModel<CommonSearchValues, IQueryable<UserMemo>> m)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<UserMemo>>()
                {
                    PageSize = Services.DefaultPageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.UserMemoes.Where(v => v.Recuper != null && v.Recuper.DepartmentID == SiteUser.DepartmentID);

            if (!string.IsNullOrEmpty(m.SearchFrom.V0)) { var w = m.SearchFrom.V0.Trim(); d = d.Where(v => v.aspnet_Users.UserName.Contains(w)); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { var w = m.SearchFrom.V1.Trim(); d = d.Where(v => v.Title.Contains(w) || v.MemoText.Contains(w)); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { var w = DateTime.Parse(m.SearchFrom.V2); d = d.Where(v => v.CreateTime >= w); }
            if (!string.IsNullOrEmpty(m.SearchTo.V2)) { var w = DateTime.Parse(m.SearchTo.V2).AddDays(1); d = d.Where(v => v.CreateTime <= w); }

            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
            d = d.OrderByDescending(v => v.CreateTime);
            m.Data = d.Skip(m.PageSize * m.PageIdx).Take(m.PageSize);
            return ViewOrPartial(m);
        }
        [HttpGet]
        public ActionResult UserMemoEdit(string id)
        {
            return PartialView(string.IsNullOrEmpty(id) ? new UserMemo() : DB.UserMemoes.FirstOrDefault(v => v.ID == id && (v.Recuper != null && v.Recuper.DepartmentID == SiteUser.DepartmentID)));
        }

        public ActionResult RecuperAttachInfoMgr()
        {
            DepartmentProfile model = new DepartmentProfile
            {
                ID = Guid.NewGuid().ToString("N"),
                DepartmentID = SiteUser.DepartmentID,
                SettingKey = "EnHospital",
                SettingValueB = "System.String",
                SettingValueC = "20"
            };
            return View(model);
        }
        [HttpPost]
        public ActionResult RecuperAttachInfoMgr(DepartmentProfile model)
        {
            if (ModelState.IsValid)
            {
                if (SiteUser.Department.DepartmentProfiles.Count(p => p.SettingKey == model.SettingKey
                    && p.SettingValue == model.SettingValue.Trim()) > 0)
                {
                    ModelState.AddModelError("", "属性“" + model.SettingValue + "”已存在！");
                    return View(model);
                }
                int maxSortIdx = SiteUser.Department.DepartmentProfiles.Count(p => p.SettingKey == model.SettingKey) > 0
                    ? SiteUser.Department.DepartmentProfiles.Where(p => p.SettingKey == model.SettingKey).Max(p => p.SortIdx) : 0;
                model.ID = DB.NewID();
                model.SettingValue = model.SettingValue.Trim();
                model.SortIdx = maxSortIdx + 1;
                model.Timemark = DateTime.Now;
                DB.DepartmentProfiles.AddObject(model);
                if (DB.SaveChanges() > 0)
                {
                    return View(new DepartmentProfile
                    {
                        ID = Guid.NewGuid().ToString("N"),
                        DepartmentID = SiteUser.DepartmentID,
                        SettingKey = model.SettingKey,
                        SettingValueB = "System.String",
                        SettingValueC = "20"
                    });
                }
                ModelState.AddModelError("", "添加失败！");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult RecuperAttachInfoEdit(string id, string name, int length)
        {
            if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(name))
            {
                return Json(new { result = "error", message = "属性ID和属性名称不能为空！", id = id, name = name, len = length });
            }
            try
            {
                var profile = DB.DepartmentProfiles.SingleOrDefault(p => p.ID == id);
                if (profile == null)
                {
                    return Json(new { result = "error", message = "无法找到该属性！", id = id, name = name, len = length });
                }
                var exist = SiteUser.Department.DepartmentProfiles.Count(p => p.ID != id && p.SettingKey == profile.SettingKey && p.SettingValue == name) > 0;
                if (exist)
                {
                    return Json(new { result = "error", message = "该属性名称已存在！", id = id, name = name, len = length });
                }
                profile.SettingValue = name;
                profile.SettingValueC = length.ToString();
                if (profile.RecuperAttachInfos != null && profile.RecuperAttachInfos.Count() > 0)
                {
                    foreach (var attach in profile.RecuperAttachInfos)
                    {
                        attach.AttachTitle = name;
                    }
                }
                if (DB.SaveChanges() > 0)
                {
                    return Json(new { result = "success", message = "修改成功！", id = id, name = name, len = length });
                }
                else
                {
                    return Json(new { result = "error", message = "修改失败！", id = id, name = name, len = length });
                }
            }
            catch
            {
                return Json(new { result = "error", message = "修改失败！", id = id, name = name, len = length });
            }
        }

        public ActionResult RecuperAttachInfoPartial(string type, string recuperId)
        {
            List<RecuperAttachInfo> model = new List<RecuperAttachInfo>();
            var profiles = SiteUser.Department.DepartmentProfiles
                .Where(p => p.SettingKey == type).OrderBy(p => Convert.ToInt32(p.SettingValueC)).ThenBy(p => p.SortIdx);
            foreach (var p in profiles)
            {
                RecuperAttachInfo attach = null;
                if (!String.IsNullOrEmpty(recuperId))
                {
                    attach = p.RecuperAttachInfos.SingleOrDefault(a => a.RecuperID == recuperId);
                }
                if (attach == null)
                {
                    attach = new RecuperAttachInfo
                    {
                        ID = Guid.NewGuid().ToString(), //临时的，Post时重新用DB.NewID()赋值
                        DepartProfilesID = p.ID,
                        DepartmentProfile = p,
                        AttachTitle = p.SettingValue
                    };
                    switch (p.SettingValueB)
                    {
                        case "System.Int32":
                        case "System.Double":
                            attach.AttachValue = "0";
                            break;
                        case "System.DateTime":
                            attach.AttachValue = DateTime.Now.ToString("yyyy-MM-dd");
                            break;
                        case "System.Boolean":
                            attach.AttachValue = "True";
                            break;
                        default:
                            attach.AttachValue = String.Empty;
                            break;
                    }
                }
                model.Add(attach);
            }
            return PartialView("RecuperAttachInfoPartial", model);
        }

        public ActionResult TagTemplateMgr(string Key)
        {
            var list = SiteUser.Department.DepartmentProfiles
                .Where(p => p.SettingKey.Equals(Key, StringComparison.OrdinalIgnoreCase))
                .OrderBy(p => p.SortIdx).Select(p => p.SettingValue).ToList();
            string settingValues = (list != null && list.Count > 0) ? String.Join(",", list) : string.Empty;
            KeyValuePair<string, string> model = new KeyValuePair<string, string>(Key, settingValues);
            return View(model);
        }

        [HttpPost]
        public ActionResult TagTemplateMgr(string Key, string Values)
        {
            ViewBag.Success = false;
            if (!String.IsNullOrEmpty(Key) && !String.IsNullOrEmpty(Values))
            {
                string[] settingValues = Values.Split(new char[3] { ',', ';', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                if (settingValues != null && settingValues.Length > 0)
                {
                    var list = SiteUser.Department.DepartmentProfiles
                        .Where(p => p.SettingKey.Equals(Key, StringComparison.OrdinalIgnoreCase));
                    List<DepartmentProfile> removedSettings = new List<DepartmentProfile>();
                    List<string> valueList = settingValues.ToList();
                    if (list != null && list.Count() > 0)
                    {
                        foreach (var p in list)
                        {
                            if (!valueList.Exists(v => v == p.SettingValue))
                            {
                                removedSettings.Add(p);
                            }
                        }
                        foreach (var p in removedSettings)
                        {
                            DB.DepartmentProfiles.DeleteObject(p);
                        }
                        foreach (string v in settingValues)
                        {
                            if (list.Count(p => p.SettingValue == v) == 0)
                            {
                                DB.DepartmentProfiles.AddObject(new DepartmentProfile
                                {
                                    ID = DB.NewID(),
                                    DepartmentID = SiteUser.DepartmentID,
                                    SettingKey = Key,
                                    SettingValue = v,
                                    Timemark = DateTime.Now
                                });
                            }
                        }
                    }
                    else
                    {
                        foreach (string v in settingValues)
                        {

                            DB.DepartmentProfiles.AddObject(new DepartmentProfile
                            {
                                ID = DB.NewID(),
                                DepartmentID = SiteUser.DepartmentID,
                                SettingKey = Key,
                                SettingValue = v,
                                Timemark = DateTime.Now
                            });
                        }
                    }
                    if (DB.SaveChanges() > 0)
                    {
                        ViewBag.Success = true;
                    }
                    else
                    {
                        ViewBag.ErrorMessage = "保存失败，请检查定制内容是否正确！";
                    }
                }
                else
                {
                    ViewBag.ErrorMessage = "定制内容格式不正确！";
                }
            }
            else
            {
                ViewBag.ErrorMessage = "定制类型和定制内容不能为空！";
            }
            return View(new KeyValuePair<string, string>(Key, Values));
        }
    }
}
